<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="800px" @open="open" @close="close">
    <el-form class="tl-form taskForm" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务名称" prop="taskname">
            <el-input v-model="model.taskname" type="text" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="更新内容" prop="taskfeedbackdetail" :rules="rules.validateRequire">
            <el-input v-model="model.taskfeedbackdetail" type="textarea" :rows="4" maxlength="800"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务进度" prop="taskschedule" :rules="rules.validateRequire">
            <el-input-number v-model="model.taskschedule" controls-position="right" :step="1" :disabled="isedittaskschedule" @change="changetaskschedule" :min="0" :max="maxtaskschedule" class="unitInputNumber"></el-input-number><span class="unitSpan">%</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际完成日期" prop="taskactualenddate">
            <el-date-picker v-model="model.taskactualenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="isFinish" @change="taskactualenddate" :picker-options="pickerOptions"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="更新人姓名" prop="username">
            <el-input v-model="model.username" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新人工号" prop="usercode">
            <el-input v-model="model.usercode" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planstartdate">
            <el-input v-model="model.planstartdate" :disabled="true" :formatter="dateFormat"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划完成日期" prop="planenddate">
            <el-input v-model="model.planenddate" :disabled="true" :formatter="dateFormat"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务派发日期" prop="taskdistributedate">
            <el-input v-model="model.taskdistributedate" :disabled="true" :formatter="dateFormat"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="GpmProjectTaskFeedback" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <tl-attachment sourceType="GpmProjectTaskFeedback" :sourceId="model.id" :disabled="disableAttachmentButton"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交更新
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <!-- <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button> -->
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@/views/gpm/gpmProjectInfo/mixin/mixin_page_fields_custom.js'
import { formatDate } from '@tapui/utils/date'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_page_fields_custom],
  components: {},
  data() {
    return {
      moduleTitle: '任务进度更新',
      urlPrefix: '/sd/projectTaskFeedback/',
      url: {
        // 额外的url
        queryCodeList: '/sd/projectTask/dataCodeList'
      },
      disableAttachmentButton: true,
      isedittaskschedule: false,
      maxtaskschedule: 100,
      pickerOptions: {
        disabledDate: time => {
          let now = new Date()
          now.setHours(0, 0, 0, 0)
          return time.getTime() > now.getTime()
        }
      }
    }
  },
  computed: {
    isFinish() {
      return !(this.model.taskschedule >= 100)
    }
  },
  methods: {
    changenewfund() {
      // this.model.taskschedule = parseInt(this.model.newfund / this.model.fund * 100)
      this.model.taskschedule = parseFloat(this.model.newfund / this.model.fund * 100).toFixed(2)
    },
    // 格式化日期 yyyy-MM-dd
    dateFormat(row, column, cellValue, index) {
      let dateValue = row[column.property]
      if (dateValue && dateValue.length > 0) {
        return formatDate(new Date(dateValue.replace(new RegExp(/-/gm), '/')), 'yyyy-MM-dd')
      } else {
        return ''
      }
    },
    taskactualenddate(e) {
      var taskactualstartdate = new Date(this.model.taskactualstartdate).getTime()
      var taskactualenddate = new Date(this.model.taskactualenddate).getTime()
      var nowdate = new Date().getTime()
      if (taskactualenddate > nowdate) {
        this.$tap.alert('任务实际完成日期不能晚于当前日期！', 'warning')
        this.model.taskactualenddate = null
        return
      }
      if (taskactualenddate < taskactualstartdate) {
        this.$tap.alert('任务实际完成日期不能早于任务实际开始日期！', 'warning')
        this.model.taskactualenddate = null
        return
      }
    },
    changetaskschedule() {
      if (this.model.taskschedule >= 100) {
        // this.isFinish = false
      } else {
        // this.isFinish = true
        this.model.taskactualenddate = null
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'feedbackdate', new Date())
        this.$set(this.model, 'taskid', this.taskid)
        this.$set(this.model, 'taskname', this.taskname)
        this.$set(this.model, 'taskschedule', this.taskschedule)
        this.$set(this.model, 'taskstate', this.taskstate)
        this.planstartdate = this.planstartdate.substring(0, 10)
        this.planenddate = this.planenddate.substring(0, 10)
        this.taskdistributedate = this.taskdistributedate.substring(0, 10)
        this.$set(this.model, 'planstartdate', this.planstartdate)
        this.$set(this.model, 'planenddate', this.planenddate)
        this.$set(this.model, 'taskdistributedate', this.taskdistributedate)
        this.$set(this.model, 'projectcode', this.projectcode)
        this.$set(this.model, 'taskactualstartdate', this.taskactualstartdate)
        this.$set(this.model, 'newamount', this.newamount)
        this.$set(this.model, 'isdelivery', this.isdelivery)
        this.$set(this.model, 'newfund', this.newfund)
        this.$set(this.model, 'productline', this.productline)
        this.$set(this.model, 'productbigtype', this.productbigtype)
        this.$set(this.model, 'productmiddletype', this.productmiddletype)
        this.$set(this.model, 'productname', this.productname)
        this.$set(this.model, 'amount', this.amount)
        this.$set(this.model, 'fund', this.fund)
      }
    },
    loaded() {
      this.disableAttachmentButton = true
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'GpmProjectTaskFeedback',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      } else if (this.isAdd === false && this.disableEditSubmit === false) {
        this.disableAttachmentButton = false
      }
      if (this.model.isdelivery === '1') {
        this.maxtaskschedule = 200
        this.isedittaskschedule = true
        if (this.model.id) {
          // this.model.taskschedule = parseInt(this.model.newfund / this.model.fund * 100)
          this.model.taskschedule = parseFloat(this.model.newfund / this.model.fund * 100).toFixed(2)
        }
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    /** 保存确认 */
    // doSubmitEdit() {
    //   if (!this.beforeSubmit()) {
    //     return
    //   }
    //   this.$refs.form.validate(valid => {
    //     if (valid) {
    //       if (this.isAdd) {
    //         this.doAdd()
    //         return true
    //       } else {
    //         this.doEdit()
    //       }
    //     } else {
    //       return false
    //     }
    //   })
    // },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      postAction(this.url.add + '?billuid=' + this.uid, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            // 对返回的日期进行处理
            res.result.planstartdate = res.result.planstartdate.substring(0, 10)
            res.result.planenddate = res.result.planenddate.substring(0, 10)
            res.result.taskdistributedate = res.result.taskdistributedate.substring(0, 10)
            this.model = res.result
            this.disableAttachmentButton = false
            this.isAdd = false
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 提交审批 */
    doSubmitApproval() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.model.taskschedule >= 100 && !this.model.taskactualenddate) {
            this.$tap.alert('请填写实际完成日期！')
            return
          }
          if (this.model.taskschedule >= 100 && this.model.newamount < this.model.amount) {
            this.$tap.alert('任务完成时，当前已完成数量不应少于任务数量！')
            return
          }
          if (this.model.taskschedule < 100 && this.model.taskactualenddate) {
            this.$tap.alert('任务进度未到100%，请删除实际完成日期！')
            return
          }
          if (this.model.taskschedule < 100) {
            this.$set(this.model, 'taskactualenddate', '')
          }
          // if (this.model.taskactualenddate !== '') {
          //   var a = new Date(this.model.taskdistributedate)
          //   var b = new Date(this.model.taskactualenddate)
          //   if (a.getTime() > b.getTime()) {
          //     this.$tap.alert('实际完成日期不能小于任务派发日期！')
          //     return
          //   }
          // }
          if (this.model.taskactualenddate !== '') {
            var a = new Date(this.model.taskdistributedate)
            var b = new Date(this.model.taskactualenddate)
            if (a.getTime() > b.getTime()) {
              this.$tap.alert('实际完成日期不能小于任务派发日期！')
              return
            }
          }
          if (this.model.taskschedule >= 100) {
            this.$set(this.model, 'taskstate', '2')
          }
          // if (this.model.taskstate === '2') {
          //   this.$set(this.model, 'taskschedule', 100)
          // }
          if (this.model.taskstate === '0') {
            this.$tap.alert('任务已开始，请选择正确的任务状态!', 'warning')
            return
          }
          if (!this.url.submit) {
            this.$tap.alert('请设置审批地址!', 'warning')
            return
          }
          if (!this.beforeApproval()) {
            return
          }
          this.submitLoading = true
          this.$tap
            .confirm('确定提交更新吗？提交后，更新内容不可修改！')
            .then((_) => {
              putAction(this.url.submit, this.model).then((res) => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.afterApproval()
                  this.visible = false
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.submitLoading = false
              })
            })
            .catch((_) => {
              this.submitLoading = false
            })
        }
      })
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(async () => {
        await this.getFieldsCustomSetting('sdProjectTaskFeedbackEdit', 'el-form')
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
      })
      this.isedittaskschedule = false
    }
  },
  created() {
    this.doQueryCode()
  },
  /**  查询编码表*/
  doQueryCode() {
    if (this.url.queryCodeList) {
      getAction(this.url.queryCodeList, {}).then((res) => {
        if (res.success) {
          this.codeModel = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.taskForm {
  margin-top: 15px;
  margin-left: -50px;
  .el-row {
    margin-bottom: 2px;
  }
}
</style>
